//
//  FindFriendViewController.m
//  YMIM
//
//  Created by admin on 2022/3/23.
//

#import "AddFriendViewController.h"
#import <Masonry/Masonry.h>
#import "FriendTableViewCell.h"
#import "UIViewController+HUD.h"
#import "AddFriendActionView.h"
#import <MJExtension/MJExtension.h>

@interface AddFriendViewController ()<UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong)UISearchBar *searchBar;
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *dataArray;
@property (nonatomic,strong)AddFriendActionView *addFriendActionView;

@end

@implementation AddFriendViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"添加好友";
    self.view.backgroundColor = [UIColor whiteColor];
    [self initSearchBar];
    [self.view addSubview:self.tableView];
    self.dataArray = [NSMutableArray array];
    // Do any additional setup after loading the view.
}

-(void)initSearchBar{
  
    _searchBar = [[UISearchBar alloc] init];
    _searchBar.backgroundColor = [UIColor clearColor];
    _searchBar.showsCancelButton = NO;
    _searchBar.keyboardType = UIKeyboardTypeDefault;
    _searchBar.delegate = self;
    _searchBar.tintColor = [UIColor whiteColor];
    _searchBar.placeholder = @"搜索用户";
    [_searchBar setBackgroundImage:[UIImage new]];
    if (@available(iOS 13.0, *)) {
        
        UITextField * textField = self.searchBar.searchTextField;
        textField.backgroundColor =  [UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1];
        textField.layer.cornerRadius = 15;
        textField.clipsToBounds = YES;
        UIColor *color = [UIColor grayColor];
        [textField setAttributedPlaceholder:[[NSAttributedString alloc] initWithString:@"搜索用户" attributes:@{NSForegroundColorAttributeName:color}]];
    }else{
        
        UITextField * textField = [self.searchBar valueForKey:@"searchField"];
        textField.backgroundColor =  [UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1];
        textField.layer.cornerRadius = 15;
        textField.clipsToBounds = YES;
        UIColor *color = [UIColor grayColor];
        [textField setAttributedPlaceholder:[[NSAttributedString alloc] initWithString:@"搜索用户" attributes:@{NSForegroundColorAttributeName:color}]];
        
    }

    [self.view addSubview:_searchBar];
    [self.searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.top.mas_equalTo(self.view.mas_top).offset(15);
        make.left.mas_equalTo(self.view.mas_left).offset(10);
        make.right.mas_equalTo(self.view.mas_right).offset(-10);
        make.height.mas_equalTo(50);
        
    }];
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataArray.count;
    
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *identifier = @"cell";
    FriendTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
    if (cell == nil) {
        
        cell = [[FriendTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        
    }
    cell.friendInfo = [self.dataArray objectAtIndex:indexPath.row];
    [cell.addButton addTarget:self action:@selector(addFriend:) forControlEvents:UIControlEventTouchUpInside];
    cell.addButton.tag = indexPath.row;
    cell.backgroundColor =  [UIColor whiteColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
    
}


-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    
    [[YMIMClient sharedClient].chatManager searchUserListWithKeyword:searchBar.text completion:^(NSArray<YMUserInfo *> * _Nonnull userList, YMErrorCode code) {
       
        NSDictionary *dic = (NSDictionary *)[[NSUserDefaults standardUserDefaults] objectForKey:@"userInfo"];
        YMUserInfo *userInfo = [YMUserInfo mj_objectWithKeyValues:dic];
      
        if (userList.count==0) {
            
            [self.dataArray removeAllObjects];
            [self.tableView reloadData];
            [self showHint:@"用户不存在"];
            return;
        }
        
        [self.dataArray removeAllObjects];
        for (int i = 0; i<userList.count; i++) {
            
            YMUserInfo *ymUserInfo = userList[i];
            YMFriendInfo *friendInfo = [YMFriendInfo new];
            friendInfo.friendName = ymUserInfo.userName;
            friendInfo.friendAvatar = ymUserInfo.userAvatar;
            friendInfo.friendId = ymUserInfo.userId;
            [self.dataArray addObject:friendInfo];
        }
      
        for (int i = 0; i<self.dataArray.count; i++) {
            
            YMFriendInfo *info = self.dataArray[i];
            if ([info.friendId isEqualToString:userInfo.userId]) {
                
                [self.dataArray removeObjectAtIndex:i];
            }
        }
        [self.tableView reloadData];
    }];

    
}
-(void)addFriend:(UIButton *)sender{

    [self.searchBar resignFirstResponder];
    self.addFriendActionView = [[AddFriendActionView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    self.addFriendActionView.backgroundColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.3];
    [self.addFriendActionView show];
    __weak typeof(self) weakself = self;
    [self.addFriendActionView setDidToolTextBlock:^(NSString * _Nonnull text) {
       
        YMFriendInfo *friendInfo = [weakself.dataArray objectAtIndex:sender.tag];

        [[YMIMClient sharedClient].friendManager applyAddFriendWithTargetId:friendInfo.friendId applyMessage:text completion:^(YMErrorCode code) {
            
            [weakself showHint:@"已发出好友请求"];
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:sender.tag inSection:0];
            FriendTableViewCell *cell = [weakself.tableView cellForRowAtIndexPath:indexPath];
            cell.addButton.backgroundColor = [UIColor grayColor];
            [cell.addButton setTitle:@"已申请" forState:UIControlStateNormal];
            cell.addButton.userInteractionEnabled = NO;
            
        }];
    }];
    
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 70;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.01f;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    return nil;
      
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.view endEditing:YES];
}
-(void)tapKeyBoardTypeDissmiss{
    
    [self.view endEditing:YES];

}

- (UITableView *)tableView {
    if (!_tableView) {
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 79, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height-145) style:UITableViewStylePlain];
        _tableView.tableFooterView = [[UIView alloc]init];
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.estimatedRowHeight           = 50;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;//UIScrollView也适用
        }
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0;
        }
        _tableView.showsVerticalScrollIndicator = NO;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapKeyBoardTypeDissmiss)];
        [_tableView addGestureRecognizer:tap];

    }
    return _tableView;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
